package com.movie.service.impl;

import com.movie.dto.ActorDTO;
import com.movie.dto.PageResponse;
import com.movie.entity.Actor;
import com.movie.repository.ActorRepository;
import com.movie.service.ActorService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class ActorServiceImpl implements ActorService {
    
    private final ActorRepository actorRepository;
    
    @Override
    public PageResponse<ActorDTO> getAllActors(int page, int size, String keyword) {
        Pageable pageable = PageRequest.of(page, size);
        Page<Actor> actorPage;
        
        if (keyword != null && !keyword.trim().isEmpty()) {
            actorPage = actorRepository.searchByName(keyword.trim(), pageable);
        } else {
            actorPage = actorRepository.findAll(pageable);
        }
        
        List<ActorDTO> actorDTOs = actorPage.getContent().stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
        
        PageResponse<ActorDTO> response = new PageResponse<>();
        response.setContent(actorDTOs);
        response.setPage(actorPage.getNumber());
        response.setSize(actorPage.getSize());
        response.setTotalElements(actorPage.getTotalElements());
        response.setTotalPages(actorPage.getTotalPages());
        response.setHasPrevious(actorPage.hasPrevious());
        response.setHasNext(actorPage.hasNext());
        return response;
    }
    
    @Override
    public ActorDTO getActorById(Long id) {
        Actor actor = actorRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("演员不存在"));
        return convertToDTO(actor);
    }
    
    @Override
    public ActorDTO createActor(ActorDTO actorDTO) {
        // 检查演员是否已存在
        Optional<Actor> existingActor = actorRepository.findByName(actorDTO.getName());
        if (existingActor.isPresent()) {
            throw new RuntimeException("演员已存在");
        }
        
        Actor actor = new Actor();
        actor.setName(actorDTO.getName());
        actor.setAvatar(actorDTO.getAvatar());
        actor.setDescription(actorDTO.getDescription());
        actor.setNationality(actorDTO.getNationality());
        actor.setBirthday(actorDTO.getBirthday());
        
        Actor savedActor = actorRepository.save(actor);
        return convertToDTO(savedActor);
    }
    
    @Override
    public ActorDTO updateActor(Long id, ActorDTO actorDTO) {
        Actor actor = actorRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("演员不存在"));
        
        // 检查名称是否重复（排除当前演员）
        Optional<Actor> existingActor = actorRepository.findByName(actorDTO.getName());
        if (existingActor.isPresent() && !existingActor.get().getId().equals(id)) {
            throw new RuntimeException("演员名称已存在");
        }
        
        actor.setName(actorDTO.getName());
        actor.setAvatar(actorDTO.getAvatar());
        actor.setDescription(actorDTO.getDescription());
        actor.setNationality(actorDTO.getNationality());
        actor.setBirthday(actorDTO.getBirthday());
        
        Actor updatedActor = actorRepository.save(actor);
        return convertToDTO(updatedActor);
    }
    
    @Override
    public void deleteActor(Long id) {
        Actor actor = actorRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("演员不存在"));
        actorRepository.delete(actor);
    }
    
    @Override
    public List<ActorDTO> searchActors(String keyword) {
        List<Actor> actors = actorRepository.findByNameContainingIgnoreCase(keyword);
        return actors.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
    
    @Override
    public List<Actor> findOrCreateActors(List<String> actorNames) {
        return actorNames.stream()
                .map(name -> {
                    Optional<Actor> existingActor = actorRepository.findByName(name);
                    if (existingActor.isPresent()) {
                        return existingActor.get();
                    } else {
                        Actor newActor = new Actor();
                        newActor.setName(name);
                        newActor.setCreatedAt(LocalDateTime.now());
                        return actorRepository.save(newActor);
                    }
                })
                .collect(Collectors.toList());
    }
    
    private ActorDTO convertToDTO(Actor actor) {
        ActorDTO dto = new ActorDTO();
        dto.setId(actor.getId());
        dto.setName(actor.getName());
        dto.setAvatar(actor.getAvatar());
        dto.setDescription(actor.getDescription());
        dto.setNationality(actor.getNationality());
        dto.setBirthday(actor.getBirthday());
        dto.setCreatedAt(actor.getCreatedAt());
        dto.setUpdatedAt(actor.getUpdatedAt());
        return dto;
    }
}